<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: rainfer <81818832@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

// use app\admin\model\MemberList;
use app\admin\controller\Loginlog;
use app\admin\model\FlowGroupUser as FlowGroupUserModel;
use think\Model;
use think\Db;

/**
 * 后台用户模型
 * @package app\admin\model
 */
class User extends Person
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = false;

    /***用户类型配置***/
    protected $confUserType = array(
        'super_admin' => -1,    //超级管理员
        'city_admin' => -2,   //城市管理员
        'compay_user' => 1, //运营公司用户
        'agent_user' => 2, //中介公司用户
        'bank_user' => 3, //银行用户
        'insurer' => 4, //保险公司用户
        'buyer' => 5, //买方
        'seller' => 6 //卖方
    );

    //用户类型
        private $tt = array(
            "1" => "公司",
            "2" => "开发商"
        );

        //获取用户类型
        public function UserType(){
            return $this->tt;
        }

    /***用户类型配置描述***/
    protected $confUserTypeText = array(
        '-1' => '超级管理员',
        '-2' => '城市管理员',
        '1' => '运营公司用户',
        '2' => '中介公司用户',
        '3' => '银行用户',
        '4' => '保险公司用户',
        '5' => '买方',
        '6' => '卖方'
    );

    /***用户状态描述***/
    protected $confUserValidText = array(
        '0' => '禁用',
        '1' => '启用',
    );

    /***员工合同类型***/
    protected $confHtType = array(
        '1' => '劳动合同',
        '2' => '其他',
    );

    /***员工合同状态类型***/
    protected $confHtStatusType = array(
        '0' => '待执行',
        '1' => '生效中',
        '2' => '已终止',
        '3' => '已过期'
    );

    /*
     * 用户类型配置
     * @param one
     * @return  array  用户类型配置
     */
    public function getConfUserType()
    {
        return $this->confUserType;
    }


    /*
     * 用户类型配置描述
     * @param one
     * @return  array  用户类型描述
     */
    public function getConfUserTypeText()
    {
        return $this->confUserTypeText;
    }


    /*
     * 用户状态配置
     * @param one
     * @return  array  用户状态描述
     */
    public function getConfUserValidText()
    {
        return $this->confUserValidText;
    }


    /*
     * 合同类型配置
     * @param one
     * @return  array  合同类型配置
     */
    public function getHtType()
    {
        return $this->confHtType;
    }


    /*
     * 合同状态类型配置
     * @param one
     * @return  array  合同状态类型配置
     */
    public function getHtStatusType()
    {
        return $this->confHtStatusType;
    }

    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @param bool $rememberme 记住登录
     * @return bool|mixed
     */
    public function login($username = '', $password = '', $doginfo = "",$rememberme = false)
    {
        $username = trim($username);
        $password = trim($password);
        $doginfo = xmlToArray($doginfo);
        $map['user_name'] = $username;
        $map['isvalid'] = 1;
        $user = self::get($map);
        if (!$user) {
            $this->error = '用户不存在或被禁用！';
        } else {
            
            if (md5($password) !== $user['password']) {
                $this->error = '密码错误！';
            } else {
                $aid = $user['id'];
                // 更新登录信息
                $user['last_login_ip']   = request()->ip();
                $user['last_login_time'] = time();
                $user['admin_hits'] = $user['admin_hits'] + 1;
                if ($user->save()) {
                    // 自动登录
                    $user_info = Db::name('user')->where(array('id'=>$aid))->find();
                    $user_info['password'] = $password;
                    $this->auto_login($user_info, $rememberme);
                }
                return $aid;
            }
        }
        return false;
    }

    /**
     * 根据user_id直接登陆
     * @param int user_id 用户id
     * @return bool|mixed
     */
    public function loginById($user_id)
    {
        $user_id = intval($user_id);
        $map['id']=$user_id;
        $map['isvalid'] = 1;
        $user = self::get($map);
        if (!$user) {
            $this->error = '用户不存在或被禁用！';
        } else {
                $aid = $user['id'];
                // 更新登录信息
                $user['last_login_ip']   = request()->ip();
                $user['last_login_time'] = time();
                $user['admin_hits'] = $user['admin_hits']+1;
                if ($user->save()) {
                    // 自动登录
                    $user_info = Db::name('user')->where(array('id'=>$aid))->find();
                    $this->auto_login($user_info);
                }
                return $aid;
        }
        return false;
    }

    /**
     * 自动登录
     * @param mixed $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     */
    public function auto_login($user, $rememberme = false)
    {
	// 用户信息存入session
        $userinfo = array(
            'id'                => $user['id'],
            'dept_id'           => $user['dept_id'],
            'org_id'            => $user['org_id'],
            'sex'               => $user['sex'],
            'user_type'         => $user['user_type'],
            'name'              => $user['name'],
            'user_name'         => $user['user_name'],
            'password'          => $user['password'],
            'login_ip'          => $user['last_login_ip'],
            'login_time'        => $user['last_login_time'],
            'position'          => $user['position']
        );
        /***用户其他信息存入session***/
        //职务
        $position_name = '';
        if(isset($user['position']) && !empty($user['position'])){
            $position_data = Db::name('position')->where(array('id'=>intval($user['position'])))->find();
            if(is_array($position_data) && !empty($position_data)){
                $position_name = $position_data['name'];
            }
        }
        $userinfo['position_name'] = $position_name;
        //部门
        $dept_name = "";
        if(isset($user['dept_id']) && !empty($user['dept_id'])){
            $dept_data = Db::name('dept')->where(array('id'=>intval($user['dept_id'])))->find();
            if(is_array($dept_data) && !empty($dept_data)){
                $dept_name = $dept_data['name'];
            }
        }
        $userinfo['dept_name'] = $dept_name;
        //所属用户组
        $auth_group_arr = array();
        if(isset($user['id']) && !empty($user['id'])){
            $group_data = Db::name('auth_group_access')->where(array('uid'=>intval($user['id'])))->select();
            if(is_array($group_data) && !empty($group_data)){
                foreach ($group_data as $key => $val){
                    $auth_group_arr[] = $val['group_id'];
                }
            }
        }
        $userinfo['auth_group_id'] = $auth_group_arr;
        //所属流程用户组
        $flow_group_user_model = new FlowGroupUserModel();
        $flow_group_arr = $flow_group_user_model->getUserAuthGroup($user['id']);
        $userinfo['group_id'] = $flow_group_arr;

        session('userinfo', $userinfo);
	session('admin_auth_sign', data_signature($userinfo));

        // 记住登录
        if ($rememberme) {
            $signin_token = $user['user_name'].$user['id'].$user['login_time'];
            cookie('aid', $user['id'], 24 * 3600 * 7);
            cookie('signin_token', data_signature($signin_token), 24 * 3600 * 7);
        }

        //登陆日志
        $user_data = session('userinfo');
        $add_data = array(
            'uid' => $user_data['id'],
            'uname' => $user_data['user_name'],
            'ip' => trim($_SERVER['REMOTE_ADDR']),
            'time' => time()
        );
        Db::name('login_log')->insert($add_data);
     }

    /**
     * 判断是否登录
     * @return int 0或用户id
     */
    public function is_login()
    {
        $user = session('userinfo');
        if (empty($user)) {
            if (cookie('?aid') && cookie('?signin_token')) {
                $user = $this::get(cookie('aid'));
                if ($user) {
                    $signin_token = data_signature($user['user_name'].$user['id'].$user['login_time']);
                    if (cookie('signin_token') == $signin_token) {
                        $this->auto_login($user, true);
                        return $user['id'];
                    }
                }
            };
            return 0;
        }else{
            return session('admin_auth_sign') == data_signature($user) ? $user['id'] : 0;
        }
    }

    /**
     * 添加用户
     */
    public function add($add_data = array() , $group_id_arr = array())
    {
        $result = false;

        // 启动事务
        Db::startTrans();
        try{
            //添加用户
            $add_user_result = db('user')->insertGetId($add_data);
            if(isset($add_user_result) && !empty($add_user_result)){
                //添加所属用户组数据
                $id = $add_user_result;
                $accdata = array(
                    'uid' => $id
                );
                if(is_array($group_id_arr) && !empty($group_id_arr)){
                    foreach ($group_id_arr as $key => $value){
                        $accdata['group_id'] = $value;
                        Db::name('auth_group_access')->insert($accdata);
                    }
                }


                $result = true;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $result;
    }

    /**
     * 修改管理员
     * @param array
     * @return bool
     */
    public function edit($id = 0 , $update_data = array() , $auth_group_str = '')
    {
        $result = false;
        // 启动事务
        Db::startTrans();
        try{
            $rst = self::where('id', $id)->update($update_data);
            if ($rst !== false) {
                $result = true;
                $access = Db::name('auth_group_access')->where('uid', $id)->find();
                $group_id_arr = array();
                if (isset($auth_group_str) && !empty($auth_group_str)) {
                    $group_id_arr = explode(',',$auth_group_str);
                }
                
                if(is_array($group_id_arr) && !empty($group_id_arr)){
                    if(is_array($access) && !empty($access)){
                        //先删除再增加
                        $uid = intval($access['uid']);
                        $del_result = Db::name('auth_group_access')->where('uid',$uid)->delete();
                        if(is_int($del_result) && !empty($del_result)){
                            $add_data = array(
                                'uid' => $id
                            );
                            foreach ($group_id_arr as $key => $value){
                                $add_data['group_id'] = intval($value);
                                Db::name('auth_group_access')->insert($add_data);
                            }
                        }
                    }else{
                        //直接增加
                        $add_data = array(
                            'uid' => $id
                        );
                        foreach ($group_id_arr as $key => $value){
                            $add_data['group_id'] = intval($value);
                            Db::name('auth_group_access')->insert($add_data);
                        }
                    }
                }


            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return $result;
    }
    
    /**
     * 超时登录
     * @return int 0或 int 1或int 2
     */
    public function overtime_login()
    {
        if (!empty(session('userinfo.id'))) {
            $map['id']=session('userinfo.id');
            $map['isvalid']=1;
            $user = self::get($map);
            $password = input("password");
            
            if (md5($password) !== $user['password']) {
                $data = 0;
            } else {
                $data = 1;
                session('over_time',null);
                session('last_action_time',time());
            }
        }else{
            $data = 2;
        }	
        return $data;
    }
    
    /*
     * 根据关键字查询用户数据
     * @param int  $dept_id 部门编号
     * @param int  $user_type 用户类型
     * @param int  $city_id 城市编号
     * @param int  $org_id 公司编号
     */
    public function getUserListByDeptid($dept_id = 0)
    {
        $userlist = array();
        if(isset($dept_id) && !empty($dept_id)){
            $cond_where = array();
            if(is_array($dept_id) && !empty($dept_id)) {
                $cond_where['dept_id'] = array('IN', $dept_id);
            } else if($dept_id > 0) {
                $dept_id = intval($dept_id);
                $cond_where['dept_id'] = $dept_id;
            }

            $cond_where['isvalid'] = 1;
            $userlist = db('user')->where($cond_where)->select();
        }

        return $userlist;
    }

    /*
     * 用户名是否存在
     * @param int  $dept_id 部门编号
     */
    public function checkouUserName($user_name = '')
    {
        $result = true;
        if(isset($user_name) && !empty($user_name)){
            $where_cond = array('user_name'=>$user_name);
            $user_info = db('user')->where($where_cond)->find();
            if(isset($user_info) && !empty($user_info)){
                $result = false;
            }
        }
        return $result;
    }




}
